package com.thinkingstar.iads.cs.sys.controller;

import java.util.*;

import com.thinkingstar.iads.common.jsonUtils.AjaxResult;
import org.apache.shiro.SecurityUtils;
import org.nutz.dao.Dao;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.json.Json;
import org.nutz.lang.Strings;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.Condition;
import org.nutz.dao.sql.Criteria;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.By;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

import com.thinkingstar.iads.common.config.BaseModule;
import com.thinkingstar.iads.common.config.Globals;
import com.thinkingstar.iads.common.filter.GlobalsFilter;
import com.thinkingstar.iads.common.filter.UserLoginFilter;
import com.thinkingstar.iads.common.utils.SortHashtable;
import com.thinkingstar.iads.common.utils.StringUtil;
import com.thinkingstar.iads.cs.sys.entity.SysMajor;
import com.thinkingstar.iads.cs.sys.entity.SysResource;
import com.thinkingstar.iads.cs.sys.entity.SysRole;
import com.thinkingstar.iads.cs.sys.entity.SysRoleResource;
import com.thinkingstar.iads.cs.sys.entity.SysUnit;
import com.thinkingstar.iads.cs.sys.entity.SysUserRole;
import com.thinkingstar.iads.cs.sys.entity.SysUser;

import javax.servlet.http.HttpSession;
import org.nutz.mvc.annotation.Filters;
import org.apache.commons.lang3.StringUtils;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import javax.servlet.http.HttpServletResponse;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.apache.commons.lang3.math.NumberUtils;


/**
 * @author steelwoo.cn
 * @time 2012-9-13 上午10:54:04
 * 
 */

@IocBean
@At("/private/sys/role")
@Filters({ @By(type = GlobalsFilter.class), @By(type = UserLoginFilter.class) })
public class RoleModule extends BaseModule {

	private static final String PATH = "beetl:/projectRoot/sysCenter/roles/";
    private static final String USERS_MANAGER_PATH = "beetl:/projectRoot/sysCenter/users/";

    @Inject
    protected Dao dao;

    @At
    @Ok("raw")
    public String list(@Param("roleid") int roleid,
                       @Param("page_num") int curPage, @Param("page_size") int pageSize) {
        Criteria cri = Cnd.cri();
        cri.where().andInBySql("id",
					"select userid from dc_sys_user_role where roleid=%s", roleid);
        cri.getOrderBy().asc("loginname");
        return daoCtl.listPageJson(dao, SysUser.class, curPage, pageSize, cri);
    }

	/**
	 *   角色关联的用户列表
	 * @param majorid
	 * @param curPage
	 * @param pageSize
	 * @param SearchUserName
	 * @param lock
	 * @param session
	 * @return
	 */
	@At
	@Ok("raw")
	public String userlist(@Param("majorid") String majorid,
			@Param("page") int curPage,@Param("rows") int pageSize,
			@Param("SearchUserName") String SearchUserName,@Param("lock") String lock,HttpSession session) {
		SysUser user = (SysUser) session.getAttribute("userSession");

	/*	再根据专业查用户*/
		Criteria criU=Cnd.cri();
		criU.where().andInBySql("id",
                "select userid from dc_sys_user_major where majorid=%s", majorid);
		if("1".equals(lock)){
			criU.where().and("state","=",1);
		}
		if (!"".equals(SearchUserName)) {
			SqlExpressionGroup exp = Cnd.exps("loginname", "LIKE", "%"+SearchUserName+"%").or("realname", "LIKE", "%"+SearchUserName+"%");
			criU.where().and(exp);
		} 
		criU.getOrderBy().asc("loginname");
		return daoCtl.listPageJson(dao, SysUser.class, curPage,
				pageSize, criU);
	}


	/**
	 * 所属项目列表
	 */
	@At
	@Ok("raw")
	public String projList() {
		return Json.toJson(daoCtl.list(dao, SysResource.class, Sqls.create( "select * from dc_sys_resource where LENGTH(id)=4")));
    }

	/**
	 *  新增角色
	 */
	@At
	@Ok("raw")
	public int add(@Param("..") SysRole role) {
		SysRole roleadd = daoCtl.addT(dao, role);
		return roleadd.getId();
	}

	/**
	 * 修改角色页面
	 */
	@At
	@Ok(PATH+"roleUpdate.html")
	public void toupdate(@Param("id") int id, HttpServletRequest req) {
		SysRole role = daoCtl.detailById(dao, SysRole.class, id);
		req.setAttribute("obj", role);
		req.setAttribute("pro", daoCtl.list(dao, SysResource.class, Sqls.create( "select * from dc_sys_resource where LENGTH(id)=4")));

    }

	/**
	 * 修改角色处理
	 */
	@At
	@Ok("raw")
	public boolean update(@Param("..") SysRole role) {
		return daoCtl.update(dao, role);
	}

	/**
	 * 删除角色
	 */
	@At
	public boolean delete(@Param("id") int id) {
		boolean res;
		res=daoCtl.deleteById(dao, SysRole.class, id);
		if(res){
//            daoCtl.exeUpdateBySql(dao,Sqls.create("delete from weixin_channel_role where roleid="+id));
            daoCtl.exeUpdateBySql(dao,Sqls.create("delete from dc_sys_role_resource where roleid="+id));
			daoCtl.exeUpdateBySql(dao,Sqls.create("delete from dc_sys_user_role where roleid="+id));
		}
		return res; 
	}

	@At
	@Ok("raw")
	public String ajaxunit(HttpSession session, @Param("id") String id,
			HttpServletResponse res) {
		SysUser user = (SysUser) session.getAttribute("userSession");
		if (user == null) {
			return null;
		}

		String pId = Strings.sNull(id);
		List array = new ArrayList();
		if ("".equals(pId)) {
			pId = "";
		}

		List<SysUnit> unitlist = null;
		Condition cnd;
		int sysrole = 0;
		if (user.getRolelist().contains(2)) // 判断是否为系统管理员角色
		{
			sysrole = 1;
			cnd = Cnd.where("id", "like", pId + "____").asc("location")
					.asc("id");
		} else {
			if ("".equals(pId)) {
				cnd = Cnd.where("id", "=", user.getUnitid()).asc("location")
						.asc("id");
			} else {
				cnd = Cnd.where("id", "like", pId + "____").asc("location")
						.asc("id");
			}
		}

		unitlist = daoCtl.list(dao, SysUnit.class, cnd);
		if ("".equals(pId)) {
			Map<String,Object> jsonroot = new HashMap<String, Object>();
			jsonroot.put("id", "");
			jsonroot.put("pId", "0");
			jsonroot.put("name", "机构列表");
			jsonroot.put("icon", Globals.APP_BASE_NAME
					+ "/images/icons/icon042a1.gif");
			jsonroot.put("nocheck", true);
			array.add(jsonroot);
			if (sysrole == 1) {
				Map<String,Object> jsonroot1 = new HashMap<String, Object>();
				jsonroot1.put("id", "");
				jsonroot1.put("pId", "0");
				jsonroot1.put("name", "不属于任何机构");
				jsonroot1.put("checked", true);
				array.add(jsonroot1);
			}
		}
		for (int i = 0; i < unitlist.size(); i++) { // 得到单位列表
			SysUnit unitobj = unitlist.get(i);
			String unitid = unitobj.getId();
			String pid = unitid.substring(0, unitid.length() - 4);
			if (i == 0 || "".equals(pid))
				pid = "0";
			String unitname = unitobj.getName();
			boolean sign = false;
			Condition sqlm = Cnd.wrap("id like '" + unitobj.getId() + "____'");
			int num = daoCtl.getRowCount(dao, SysUnit.class, sqlm);
			if (num > 0)
				sign = true;
			Map<String,Object> obj = new HashMap<String, Object>();
			obj.put("id", unitid);
			obj.put("pId", pid);
			obj.put("name", unitname);
			obj.put("isParent", sign);
			if (sysrole == 0 && user.getUnitid().equals(unitid)) {
				obj.put("checked", true);
			}
			array.add(obj);
		}
		return Json.toJson(array);
	}
	

	@At
	@Ok("raw")
	public String ajaxResource(HttpSession session, @Param("id") String id,
			HttpServletResponse res) {
		SysUser user = (SysUser) session.getAttribute("userSession");
		if (user == null) {
			return null;
		}

		String pId = Strings.sNull(id);
		List array = new ArrayList();
		if ("".equals(pId)) {
			pId = "";
		}

		//List<Sys_Unit> unitlist = null;
		List<SysResource> resourceList=null;
		Condition cnd;
		int sysrole = 0;
		if (user.getRolelist().contains(2)) // 判断是否为系统管理员角色
		{
			sysrole = 1;
//			cnd = Cnd.where("id", "like", pId + "____").asc("id");
		} else {
			/*if ("".equals(pId)) {
				cnd = Cnd.where("id", "=", user.getUnitid()).asc("id");
			} else {
				cnd = Cnd.where("id", "like", pId + "____").asc("location")
						.asc("id");
			}*/
		}
		//unitlist = daoCtl.list(dao, Sys_Unit.class, cnd);
		String resourceSql="select * from dc_sys_resource where id like "+"____";
		Sql sql=Sqls.create(resourceSql);
		cnd = Cnd.where("id", "like", pId + "____").asc("id");
		resourceList=daoCtl.list(dao, SysResource.class, cnd);
		if ("".equals(pId)) {
			Map<String,Object> jsonroot = new HashMap<String, Object>();
			jsonroot.put("id", "");
			jsonroot.put("pId", "0");
			jsonroot.put("name", "资源列表");
			jsonroot.put("icon", Globals.APP_BASE_NAME
					+ "/images/icons/icon042a1.gif");
			jsonroot.put("nocheck", true);
			array.add(jsonroot);
			/*if (sysrole == 1) {
				Map<String,Object> jsonroot1 = new HashMap<String, Object>();
				jsonroot1.put("id", "");
				jsonroot1.put("pId", "0");
				jsonroot1.put("name", "没有任何资源");
				jsonroot1.put("checked", true);
				array.add(jsonroot1);
			}*/
		}
		
		
		for (int i = 0; i < resourceList.size(); i++) { // 得到单位列表
			SysResource resourceobj= resourceList.get(i);
			String resourceid = resourceobj.getId();
			String pid = resourceobj.getPid();
//			boolean sign = false;
			if (!StringUtils.isNotBlank(pid)){
				pid = "0";
//				sign=true;
			}	
			String resourcename = resourceobj.getName();
			boolean sign = false;
			Condition sqlm = Cnd.wrap("id like '" + resourceobj.getId() + "____'");
			int num = daoCtl.getRowCount(dao, SysResource.class, sqlm);
			if (num > 0){
				sign = true;
			}
			Map<String,Object> obj = new HashMap<String, Object>();
			obj.put("id", resourceid);
			obj.put("pId", pid);
			obj.put("name", resourcename);
			obj.put("isParent", sign);
			array.add(obj);
		}
		String arrayStr=Json.toJson(array);
		return arrayStr;
	}

	/**
	 * 增加用户到角色
	 */
	@At
	@Ok(PATH+"roleUser.html")
	public void toaddroleuser(@Param("roleid") String roleid,
			HttpServletRequest req, HttpSession session) {

		SysUser user = (SysUser) session.getAttribute("userSession");
		roleid = Strings.sNull(roleid);
		if (user.getRolelist().contains(2 )) // 判断是否为系统管理员角色
		{
			req.setAttribute("uid", "");
		} else {
			req.setAttribute("uid", user.getUnitid());
		}
		req.setAttribute("roleid", roleid);
	}


	@At
	@Ok("raw")
	public String ajaxroleuser(HttpSession session, @Param("id") String id,
			@Param("roleid") int roleid, HttpServletResponse res) {
		SysUser user = (SysUser) session.getAttribute("userSession");
		id = Strings.sNull(id);
		List array = new ArrayList();
		if ("".equals(id)) {
			Map<String,Object> jsonroot = new HashMap<String, Object>();
			jsonroot.put("id", "");
			jsonroot.put("pId", "0");
			jsonroot.put("name", "机构列表");
			jsonroot.put("url", "javascript:list(\"\")");
			jsonroot.put("target", "_self");
			jsonroot.put("icon", Globals.APP_BASE_NAME
					+ "/images/icons/icon042a1.gif");
			array.add(jsonroot);
		}

	    /* 专业列表 start*/
	       Criteria cri = Cnd.cri();
	       if (user.getSysrole()) // 判断是否为系统管理员角色
	       {
	           cri.where().and("id", "like", id + "____");
	       } else {
	            if ("".equals(id)) {
	                cri.where().and("id", "=", user.getMajorid());
	            } else {
	                cri.where().and("id", "like", id + "____");
	            }
	       }
	       List<SysMajor> majorList=null;
			String majorSql="select * from dc_sys_major where id like"+"____";
			Sql sql=Sqls.create(majorSql);
			majorList=daoCtl.list(dao, SysMajor.class, cri);
			 int i = 0;
		        for (SysMajor major : majorList) {
		            String pid = major.getPid();
		          int num = daoCtl.getRowCount(dao, SysMajor.class,
		                    Cnd.wrap("id like '" + major.getId() + "____'"));
		            if (!StringUtils.isNotBlank(pid)){
		            	 pid = "0";
		            }
		            Map<String, Object> obj = new HashMap<String, Object>();
		            obj.put("id", major.getId());
		            obj.put("pId", pid);
		            obj.put("name", major.getName());
		            obj.put("url", "javascript:list(\"" + major.getId() + "\")");
		            obj.put("target", "_self");
		            obj.put("isParent", num > 0);
		            array.add(obj);
		            i++;
		        }
	        /*专业列表 end*/
		return Json.toJson(array);
	}

	@At
	@Ok("raw")
	public String isexistsname(@Param("name") String name) {
		String value = "";
		name = Strings.sNull(name);

		SysRole role = daoCtl.detailByName(dao, SysRole.class, "name", name);
		if (role != null) {
			value = "true";
		}
		return value;
	}

	/**
	 * 权限分配页面
	 */
	@At
	@Ok("raw")
	public String resourceTree(@Param("id") int id) {
	    //此处先从dc_sys_resource表查出button,再从dc_sys_role_resource查出勾选的button
        //需要再取消或者勾选的时候只更新dc_sys_role_resource的button字段
        Integer roleid = (Integer)SecurityUtils.getSubject().getSession().getAttribute("roleid");
		SysUser user = (SysUser)SecurityUtils.getSubject().getSession().getAttribute("userSession");
        List array=new ArrayList();
		try {
			Condition sql;
			if (user.getSysrole()==true) // 判断是否为系统管理员角色
			{
				sql = Cnd.wrap("order by location,id asc");
			} else {
				String rids = "";
				for (int i = 0; i < user.getRolelist().size(); i++) {
					if (i == user.getRolelist().size() - 1) {
						rids += user.getRolelist().get(i) + "";
					} else {
						rids +=  user.getRolelist().get(i) + ",";
					}
				}
				sql = Cnd
						.wrap("id in(select DISTINCT RESOURCEID from dc_sys_role_resource where roleid in("
								+ rids + ")) order by location,id asc");
			}
			Hashtable<String, String> rh = new Hashtable<String, String>();
			Sql htsql = Sqls
					.create("select RESOURCEID,BUTTON from dc_sys_role_resource where roleid="
							+ roleid);
			rh = daoCtl.getHTable(dao, htsql);
			List<SysResource> list = daoCtl.list(dao, SysResource.class, sql); //查的是dc_sys_resource表

            Map<String,Object> jsonroot=new HashMap<String, Object>();
			jsonroot.put("id", "");
			jsonroot.put("pId", "0");
			jsonroot.put("name", "资源列表");
			jsonroot.put("checked", false);
			jsonroot.put("nocheck", true);
			jsonroot.put("button", "");
			jsonroot.put("open", true);
			jsonroot.put("icon", Globals.APP_BASE_NAME
					+ "../../../images/icons/icon042a1.gif");
			array.add(jsonroot);
			for (int i = 0; i < list.size(); i++) {
				SysResource obj = list.get(i);
				Map<String,Object> jsonobj = new HashMap<String, Object>();
				jsonobj.put("id", obj.getId());
				jsonobj.put("pId",
						obj.getId().substring(0, obj.getId().length() - 4));
				jsonobj.put("name", obj.getName());
				if (rh != null && null != rh.get(String.valueOf(obj.getId()))) {
					jsonobj.put("checked", true);
				} else {
					jsonobj.put("checked", false);
				}
				jsonobj.put("res_button", obj.getButton());
				jsonobj.put("button", rh.get(String.valueOf(obj.getId())));
				array.add(jsonobj);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
		return Json.toJson(array);
	}

	/**
	 * 权限分配处理
	 */
	@At
	public boolean menu(@Param("checkids") String checkids,
			@Param("roleid") int roleid) {
		try {
			if (!"".equals(checkids)) {
				String[] ids =StringUtils.split(checkids, ";") ;
				Condition c = Cnd.where("roleid", "=", roleid);
				daoCtl.delete(dao, "dc_sys_role_resource", c);
				for (int i = 0; i < ids.length; i++) {
					SysRoleResource resource = new SysRoleResource();
					String[] id_Button = StringUtils.split(ids[i], ":");
					resource.setRoleid(roleid);
					resource.setResourceid(id_Button[0]);
					if (id_Button.length < 2) {
						resource.setButton("");
					} else {
						resource.setButton(id_Button[1]);
					}
					daoCtl.add(dao, resource);
				}
			} else {
				Condition c = Cnd.where("roleid", "=", roleid);
				daoCtl.delete(dao, "dc_sys_role_resource", c);
			}
			return true;

		} catch (Exception e) {
			e.printStackTrace();
		} finally {

		}
		return false;
	}


	/**
	 * 分配用户角色处理
	 */
	@At
    @Ok("raw")
	public String addroleuser(@Param("roleid") int roleid,
			@Param("checkids") String checkids, HttpSession session) {
		checkids = Strings.sNull(checkids);
		String msg = "";
		try {
			int result = 0;
			String[] ids = StringUtils.split(checkids, ",");
			for (int i = 0; i < ids.length; i++) {
				SysUserRole s = new SysUserRole();
				s.setUserid(NumberUtils.toLong(Strings.sNull(ids[i])));
				s.setRoleid(roleid);
				daoCtl.add(dao, s);
				result++;
			}
			if (result > 0) {
				msg = "true";
			}
		} catch (Exception e) {
			e.printStackTrace(); // To change body of catch statement use File |
									// Settings | File Templates.
		} finally {
		}
		return msg;
	}

	/**
	 * 删除角色中的用户
	 */
	@At
    @Ok("raw")
	public String delroleuser(@Param("checkids") String checkids,
			@Param("roleid") int roleid) {
		String[] userids = StringUtils.split(checkids, ",");
		for (int i = 0; i < userids.length; i++) {
			Condition cnd = Cnd.where("roleid", "=", roleid).and("userid",
					"=", userids[i]);
			daoCtl.delete(dao, "dc_sys_user_role", cnd);
		}
		return "true";
	}

	@At("")
	@Ok(PATH+"role.html")
	public void role(HttpSession session, @Param("unitid") String unitid1,
			HttpServletRequest req) {
		SysUser user = (SysUser) session.getAttribute("userSession");
		Sql sql = Sqls
				.create("select roleid from dc_sys_user_role where userid=@userid");
		sql.params().set("userid", user.getId());
		req.setAttribute("roleid", daoCtl.getIntRowValue(dao, sql));
	}


	@At
	@Ok("raw")
	public String tree() {
		SysUser user = (SysUser) SecurityUtils.getSubject().getSession().getAttribute("userSession");

		Condition sqlrole;
		List<SysRole> rolelist = null;

//		sqlrole = Cnd.wrap("unitid is null or unitid='' order by location,id asc");
		sqlrole = Cnd.wrap(" order by location,id asc");
		Hashtable<String, String> hm = new Hashtable<String, String>();
        List<Object> array=new ArrayList<Object>();
		Map<String,Object> jsonroot = new HashMap<String, Object>();
		jsonroot.put("id", "");
		jsonroot.put("pId", "0");
		jsonroot.put("name", "角色列表");
		jsonroot.put("checked", false);
		jsonroot.put("nocheck", true);
		jsonroot.put("open", true);
		jsonroot.put("icon", Globals.APP_BASE_NAME
				+ "../images/icons/icon042a1.gif");
		if (!"".equals(sqlrole)) {
			rolelist = daoCtl.list(dao, SysRole.class, sqlrole);
			for (int j = 0; j < rolelist.size(); j++) {

				SysRole roleobj = rolelist.get(j);
				Map<String,Object> jsonobj = new HashMap<String, Object>();
				jsonobj.put("id", String.valueOf(roleobj.getId()));
				jsonobj.put("pId", "");
				jsonobj.put("name", roleobj.getName());
				jsonobj.put("checked", false);
				jsonobj.put("url", "javascript:list(\"" + roleobj.getId()
						+ "\")");
				jsonobj.put("target", "_self");
				array.add(jsonobj);
			}
		}
		array.add(jsonroot);
		return Json.toJson(array);
	}

	@At
	@Ok("raw")
	public String getrole(@Param("roleid") int roleid) {
		return Json.toJson(daoCtl.detailById(dao, SysRole.class, roleid));
	}

    @At("/getuser")
    @Ok(USERS_MANAGER_PATH+"userInfo.html")
    public void getuser() {}

    @At
    @Ok(PATH+"roleMenuGrant.html")
    public void toMenuGrant(@Param("roleid") int roleid,HttpSession session){
	    SecurityUtils.getSubject().getSession().setAttribute("roleid",roleid);
    }


    @At("/usertree")
    @Ok("raw")
    public String getusertree(@Param("id") String id) {
        id = Strings.sNull(id);
        List<Object> array = new ArrayList<Object>();
        //直接在div上使用
        if ("".equals(id)) {
            Map<String, Object> jsonroot = new HashMap<String, Object>();
            jsonroot.put("id", "");
            jsonroot.put("pId", "0");
            jsonroot.put("name", "机构列表");
            jsonroot.put("icon", "../../../images/icons/icon042a1.gif");
            array.add(jsonroot);
        }
        Criteria cri = Cnd.cri();
        cri.where().and("id", "like", id + "____");
        cri.getOrderBy().asc("location");
        cri.getOrderBy().asc("id");

        List<SysUnit> unitlist = daoCtl.list(dao, SysUnit.class, cri);
        int i = 0;
        for (SysUnit u : unitlist) {
            String pid = u.getId().substring(0, u.getId().length() - 4);
            int num = daoCtl.getRowCount(dao, SysUnit.class,
                    Cnd.wrap("id like '" + u.getId() + "____'"));
            if (i == 0 || "".equals(pid))
                pid = "0";
            Map<String, Object> obj = new HashMap<String, Object>();
            obj.put("id", u.getId());
            obj.put("pId", pid);
            obj.put("name", u.getName());
            obj.put("url", "javascript:view(\"" + u.getId() + "\")");
            obj.put("isParent", num > 0);
            obj.put("target", "_self");
            array.add(obj);
            i++;
        }
        return Json.toJson(array);
    }




}
